var app = getApp()
const api = require('../../utils/utils')
let socketOpen = false
Page({
  data: {
    patient_id: "", // 本页面对应的患者id
    records: [], // 记录列表

    label_id: "", // 选中的标签号
    label_name: '', // 选中的标签部位
    date: "", //选择日期
    imagePath: "", // 上传图片的本地路径

    process: 0, // 预测进度
    process_show: false,
    process_msg: '',
    filePath: '', // 报告本地保存路径

    delete_record_id: '', // 删除的记录号
    popup: false
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '疤痕检测记录'
    })
    this.getRecords(options.patient_id)
    this.setData({
      patient_id: options.patient_id
    })
  },
  // 获取检测记录列表
  getRecords(patient_id) {
    const url = `/records/${patient_id}/patient/query/?page_size=10`
    api.request('get', url).then(res => {
      this.setData({
        records: res.results,
      })
    })
  },
  // 跳转到标签管理页面
  toLableList() {
    var that = this
    that.setData({
      label_id: '',
      label_name: ''
    })
    wx.navigateTo({
      url: `/pages/label/index?patient_id=${this.data.patient_id}`,
      events: {
        returnEvent: function (data) {
          api.request('get', `/labels/${that.data.patient_id}/patient/${data.label_id}/`)
            .then(res => {
              that.setData({
                label_id: res.id,
                label_name: res.name
              })
            })
        }
      },
    })
  },
  // 添加记录
  async addRecord() {
    // 校验表单
    if (this.data.label_id == '') {
      const toast = this.selectComponent("#toast")
      toast.linShow({
        title: "请选择疤痕部位",
        icon: "error",
      })
      return
    }
    if (this.data.date == '') {
      const toast = this.selectComponent("#toast")
      toast.linShow({
        title: "请选择日期",
        icon: "error",
      })
      return
    }
    if (this.data.imagePath == '') {
      const toast = this.selectComponent("#toast")
      toast.linShow({
        title: "请选择图片",
        icon: "error",
      })
      return
    }
    await this.compressImage() // 压缩图片
    this.uploadPhoto() // 上传图片

  },
  // 压缩图片
  compressImage() {
    wx.compressImage({
      src: this.data.imagePath,
      quality: 60,
      success: (res) => {
        this.setData({
          imagePath: res.tempFilePath
        })
      },
    })
  },
  // 上传record
  uploadPhoto() {
    var that = this
    wx.uploadFile({
      url: `${api.baseUrl}/records/${this.data.patient_id}/patient/`,
      filePath: this.data.imagePath, // 图片路径
      name: 'orig_image',
      formData: {
        'label': this.data.label_id,
        'record_date': this.data.date,
      },
      header: {
        "Content-Type": "multipart/form-data",
        'authorization': 'jwt ' + wx.getStorageSync('token')
      },
      // 上传成功
      success: function (res) {
        if (res.statusCode == 201) {
          const toast = that.selectComponent("#toast")
          toast.linShow({
            title: "上传成功",
            icon: "success"
          })
          that.getRecords(that.data.patient_id)
        } else {
          const toast = that.selectComponent("#toast")
          toast.linShow({
            title: "上传失败",
            icon: "error"
          })
        }
        that.setData({
          imagePath: ''
        })
      },
      fail: function (e) {
        const toast = this.selectComponent("#toast")
        toast.linShow({
          title: "上传失败",
          icon: "error"
        })
      },
    })
    this.setData({
      imagePath: ''
    })
  },
  chooseImageTap() {
    this.setData({
      popup: true
    })
  },
  chooseImage() {
    var that = this
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success(res) {
          that.setData({
            imagePath: res.tempFilePaths[0]
          })
          resolve(res)
        },
        fail(error) {
          reject(error)
        }
      })
    })
  },
  toCamera() {
    var that = this
    wx.navigateTo({
      url: '/pages/record/camera/camera',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        returnEvent: function (data) {
          that.setData({
            imagePath: data.src,
          })
        }
      },
    })
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  btn_deleteLabel(details) {
    this.setData({
      delete_record_id: details.target.id
    })
    const dialog = this.selectComponent("#dialog")
    dialog.linShow({
      title: "确认删除？",
      type: "confirm",
    })
  },
  btn_predict(details) {
    this.initWebSocket(details.target.id)
  },
  initWebSocket(record_id) {
    let that = this
    wx.connectSocket({
      url: api.wsUrl,
      header: {
        'content-type': 'application/json'
      },
      success: function (e) {
        console.log("websocket connect open ", api.wsUrl)
        socketOpen = true
        that.setData({
          process: 0,
          process_show: true
        })
      },
      fail: function (e) {
        console.log('连接失败')
        myCloseSocket()
      }
    })
    // 连接成功则发送预测命令
    wx.onSocketOpen(function (res) {
      let message = {
        id: record_id,
        token: wx.getStorageSync('token'),
      };
      wx.sendSocketMessage({
        data: JSON.stringify(message)
      })
    })
    // 打印返回的消息
    wx.onSocketMessage(function (e) {
      let msg = JSON.parse(e.data);
      console.log(msg);
      that.setData({
        process: msg.process,
        process_msg: msg.message
      })
      if (msg.process == 100) {
        myCloseSocket()
      }
    })
    // 处理错误
    wx.onSocketError(function (e) {
      console.log(e)
      myCloseSocket()
    })
    wx.onSocketClose(function (e) {
      console.log(
        "websocket connect close",
        e.code + " " + e.reason
      );
    })

    function myCloseSocket() {
      wx.closeSocket()
      setTimeout(() => {
        that.setData({
          process: 0,
          process_show: false
        })
      }, 4000);
      that.getRecords(that.data.patient_id)
    }
  },
  btn_download(event) {
    var that = this
    wx.downloadFile({
      url: api.baseUrl + `/records/${this.data.patient_id}/patient/${event.target.id}/report/`,
      header: {
        "Content-Type": "multipart/form-data",
        'authorization': 'jwt ' + wx.getStorageSync('token')
      },
      success(res) {
        if (res.statusCode === 200) {
          const toast = that.selectComponent("#toast")
          toast.linShow({
            title: "下载成功",
            icon: "success"
          })
          console.log(res.tempFilePath)
        } else {
          const toast = that.selectComponent("#toast")
          toast.linShow({
            title: "下载失败",
            icon: "error"
          })
        }
      },
      fail(e) {
        const toast = that.selectComponent("#toast")
        toast.linShow({
          title: "下载失败",
          icon: "error"
        })
      }
    })
  },
  mySaveFile(tempFilePath) {
    var that = this
    fileSys = wx.getFileSystemManager()
    fileSys.saveFile({
      tempFilePath: tempFilePath,
      filePath: that.data.filePath
    })
  },
  deleteRecord() {
    api.request('delete', `/records/${this.data.patient_id}/patient/${this.data.delete_record_id}/`, {})
      .then((res) => {
        const toast = this.selectComponent("#toast")
        toast.linShow({
          title: "删除成功",
          icon: "success"
        })
        this.getRecords(this.data.patient_id)
      })
      .catch((err) => {
        const toast = this.selectComponent("#toast")
        toast.linShow({
          title: "删除失败",
          icon: "error"
        })
      })
  },
  toExample() {
    wx.navigateTo({
      url: '/pages/record/example/example'
    })
  },
  preview(event) { // 放大预览图片
    let currentUrl = event.currentTarget.dataset.src
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: [currentUrl]
    })
  }
})